﻿using AiMoWindows.CodeScripts;
using AiMoWindows.Localization;
using AiMoWindows.MainActions.SecondaryActions;
using AiMoWindows.Server;
using AiMoWindows.Windows.SaveCode;
namespace AiMoWindows.MainActions.ScriptActions.SubActions
{
    /// <summary>
    /// 下载上传代码
    /// </summary>
    class DownloadUploadScriptAction(ActionsController actions, ScriptManager scriptManager)
    {
        readonly ActionsController actions = actions;
        readonly ScriptManager scriptManager = scriptManager;
        public async void DownloadScript()
        {
            // 实现下载脚本的逻辑
            actions.ClearDebugPrint();
            ScriptDownloader scriptDownloader = new ScriptDownloader(actions.Printer, Entrance.AiMoProgram.Instance);
            ScriptDownloadResult result = await scriptDownloader.DownloadScriptFromShareCode();
            if (result.Result)
            {
                if (!Entrance.AiMoProgram.Instance.OpenNewAimoScriptForm(result, out string error))
                {
                    actions.Printer.PrintDebug(error);
                }
            }
        }
        public async void UploadScript()
        {
            actions.ClearDebugPrint();
            if (!ServerHelper.LogInAsCommunityUser)
            {
                actions.Printer.PrintDebug(Local.Get("Only login users can share codes"));
                return;
            }
            // 实现上传脚本的逻辑
            if (!await actions.SyncAction.SyncScriptsWithFormat())
            {
                // 无法同步，格式有误
                return;
            }
            ShareSaveResult saveResult = scriptManager.ShowShareSaveInfo(SaveMode.Share);
            if (saveResult.OK)
            {
                actions.Printer.PrintDebug(Local.Get("Uploading share code to cloud in backgound. Please wait a moment."));
                await Task.Run(() =>
                {
                    PerformShareAsync(saveResult, out string printInfo);
                    actions.Printer.PrintDebug(printInfo);
                }
                );
            }
        }
        void PerformShareAsync(ShareSaveResult saveResult, out string printInfo)
        {
            if (scriptManager.ShareCodes(actions.Printer, saveResult, out printInfo))
            {
                MainActions.ActionsUtils.SetTextToClipboard(saveResult.ShareKey);
                printInfo += Environment.NewLine + Local.Get("Already sent share code to cloud. ShareKey has been copy to clipboard.") + Environment.NewLine + saveResult.ShareKey;
                MainActions.ActionsUtils.OpenWebWithShareKey(saveResult.ShareKey, saveResult.CodeName, saveResult.Description);
            }
        }
    }
}
